import random
import json
import os
from datetime import datetime, timedelta

# 诗词列表，格式：(序号, 名称)
poems = [
    (2, "江南（汉乐府）"),
    (4, "长歌行（节选）（汉乐府）"),
    (6, "七步诗（曹植）"),
    (8, "敕勒歌（北朝民歌）"),
    (10, "咏鹅(骆宾王)"),
    (12, "风（李峤）"),
    (14, "回乡偶书（少小离家老大回） （贺知章）"),
    (16, "咏柳(贺知章)"),
    (18, "凉州词（黄河远上白云间） （王之涣）"),
    (20, "登鹳雀楼（王之涣）"),
    (22, "春晓（孟浩然）"),
    (24, "宿建德江（孟浩然）"),
    (26, "凉州词（葡萄美酒夜光杯） （王翰）"),
    (28, "出塞（王昌龄）"),
    (30, "从军行（青海长云暗雪山） （王昌龄）"),
    (32, "芙蓉楼送辛渐（王昌龄）"),
    (34, "鹿柴（王维）"),
    (36, "竹里馆（王维）"),
    (38, "送元二使安西（王维）"),
    (40, "九月九日忆山东兄弟（王维）"),
    (42, "别董大（高适）"),
    (44, "静夜思（李白）"),
    (46, "古朗月行（节选）（李白）"),
    (48, "望庐山瀑布（李白）"),
    (50, "赠汪伦（李白）"),
    (52, "独坐敬亭山（李白）"),
    (54, "黄鹤楼送盂浩然之广陵（李白）"),
    (56, "早发白帝城（李白）"),
    (58, "秋浦歌（白发三千丈）（李白）"),
    (60, "望天门山（李白）"),
    (62, "闻官军收河南河北（杜甫）"),
    (64, "绝句（两个黄鹂鸣翠柳）（杜甫）"),
    (66, "赠花卿（杜甫）"),
    (68, "江南逢李龟年（杜甫）"),
    (70, "春夜喜雨（杜甫）"),
    (72, "绝句（迟日江山丽）（杜甫）"),
    (74, "江畔独步寻花（黄师塔前江水东）（杜甫）"),
    (76, "逢雪宿芙蓉山主人（刘长卿）"),
    (78, "江雪（柳宗元）"),
    (80, "寻隐者不遇（贾岛）"),
    (82, "枫桥夜泊（张继）"),
    (84, "渔歌子（张志和）"),
    (86, "早春呈水部张十八员外（韩愈）"),
    (88, "寒食（韩翃）"),
    (90, "滁州西涧（韦应物）"),
    (92, "塞下曲（月黑雁飞高）（卢纶）"),
    (94, "游子吟（孟郊）"),
    (96, "竹枝词（杨柳青青江水平）（刘禹锡）"),
    (98, "乌衣巷（刘禹锡）"),
    (100, "望洞庭（刘禹锡）"),
    (102, "浪淘沙（九曲黄河万里沙）（刘禹锡）"),
    (104, "赋得古原草送别（白居易）"),
    (106, "池上（白居易）"),
    (108, "忆江南（白居易）"),
    (110, "搁农（锄禾日当午）（李绅）"),
    (112, "悯农（春种一粒粟）（李绅）"),
    (114, "山行（杜牧）"),
    (116, "清明（杜牧）"),
    (118, "江南春（杜牧）"),
    (120, "秋夕（杜牧）"),
    (122, "乐游原（李商隐）"),
    (124, "蜂（罗隐）"),
    (126, "小儿垂钓（胡令能）"),
    (128, "商山早行（温庭筠）"),
    (130, "江上渔者（范仲淹）"),
    (132, "元日（王安石）"),
    (134, "泊船瓜洲（王安石）"),
    (136, "书湖阴先生壁（王安石）"),
    (138, "梅花（王安石）"),
    (140, "六月二十七日望湖楼醉书（苏轼）"),
    (142, "饮湖上初晴后雨（苏轼）"),
    (144, "惠崇春江晚景（苏轼）"),
    (146, "题西林壁（苏轼）"),
    (148, "夏日绝句（李清照）"),
    (150, "三衢道中（曾几）"),
    (152, "示儿（陆游）"),
    (154, "秋夜将晓出篱门迎凉有感（陆游）"),
    (156, "小池（杨万里）"),
    (158, "晓出净慈寺送林子方（杨万里）"),
    (160, "四时田园杂兴（其三十一）（范成大）"),
    (162, "四时田园杂兴（其二十五）（范成大）"),
    (164, "春日（朱熹）"),
    (166, "观书有感（朱熹）"),
    (168, "菩萨蛮·书江西造口壁（辛弃疾）"),
    (170, "题临安邸（林升）"),
    (172, "游园不值（叶绍翁）"),
    (174, "乡村四月（翁卷）"),
    (176, "墨梅（王冕）"),
    (178, "石灰吟（于谦）"),
    (180, "朝天子·咏喇叭（王磐）"),
    (182, "竹石（郑燮）"),
    (184, "所见（袁枚）"),
    (186, "己亥杂诗（龚自珍）"),
    (188, "村居（高鼎）"),
]

def load_history():
    history_file = "recite_history.json"
    if os.path.exists(history_file):
        with open(history_file, "r", encoding="utf-8") as f:
            history = json.load(f)
            # 转换字符串日期为datetime对象
            for key in history:
                if isinstance(history[key], dict) and 'last_review' in history[key]:
                    history[key]['last_review'] = datetime.fromisoformat(history[key]['last_review'])
            return history
    return {}

def save_history(history):
    # 转换datetime对象为字符串
    history_copy = {}
    for key, value in history.items():
        if isinstance(value, dict) and 'last_review' in value:
            history_copy[key] = value.copy()
            history_copy[key]['last_review'] = value['last_review'].isoformat()
        else:
            history_copy[key] = value
    
    with open("recite_history.json", "w", encoding="utf-8") as f:
        json.dump(history_copy, f, ensure_ascii=False, indent=4)

def get_review_schedule(last_review, mastery_level):
    # 根据艾宾浩斯记忆曲线和掌握程度设置复习间隔
    now = datetime.now()
    if last_review is None:
        return True
    
    intervals = {
        1: timedelta(days=1),   # 掌握程度低，1天后复习
        2: timedelta(days=2),   # 2天后复习
        3: timedelta(days=4),   # 4天后复习
        4: timedelta(days=7),   # 7天后复习
        5: timedelta(days=15),  # 15天后复习
        6: timedelta(days=30)   # 掌握程度高，30天后复习
    }
    
    interval = intervals.get(mastery_level, timedelta(days=1))
    return now - last_review >= interval

def reset_history(backup=True):
    history_file = "recite_history.json"
    if os.path.exists(history_file):
        if backup:
            backup_file = f"recite_history_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
            os.rename(history_file, backup_file)
            print(f"已将原有记录备份为：{backup_file}")
        else:
            os.remove(history_file)
        print("背诵记录已重置。")
    else:
        print("没有找到背诵记录文件。")

def main():
    os.system("title 小学生必背古诗词75+80首背诵小助手")
    print("欢迎使用小学生必背古诗词75+80首背诵小助手！")
    print("本程序将帮助你复习和记录古诗词背诵情况。\n")
    print("选择操作：")
    print("1. 开始背诵")
    print("2. 重置背诵记录（保留备份）")
    print("3. 重置背诵记录（不保留备份）")
    print("4. 退出")
    
    choice = input("请输入选项（1-4）：").strip()
    if choice == "2":
        reset_history(True)
        return
    elif choice == "3":
        confirm = input("确定要删除所有背诵记录吗？此操作不可恢复！(y/n)：").strip().lower()
        if confirm == 'y':
            reset_history(False)
        return
    elif choice == "4":
        return
    elif choice != "1":
        print("无效的选项！")
        return
        
    history = load_history()
    print("请输入要抽查的最大页码（如：20）：")
    try:
        max_num = int(input().strip())
    except ValueError:
        print("输入无效，请输入数字。")
        return

    # 生成小于输入序号的诗词词典
    selected_poems = [(num, name) for num, name in poems if num < max_num]
    if not selected_poems:
        print("没有找到小于该序号的诗词。")
        return

    # 根据记忆曲线筛选需要复习的诗词
    to_recite = []
    for num, name in selected_poems:
        poem_key = f"{num}-{name}"
        poem_history = history.get(poem_key, {'count': 0, 'mastery_level': 1, 'last_review': None})
        if not isinstance(poem_history, dict):
            poem_history = {'count': poem_history, 'mastery_level': 1, 'last_review': None}
        
        if get_review_schedule(poem_history.get('last_review'), poem_history.get('mastery_level', 1)):
            to_recite.append((num, name))
    
    if not to_recite:
        print("\n当前没有需要复习的诗词。")
        return

    random.shuffle(to_recite)
    recite_record = []
    seen_poems = set()

    print(f"\n今天需要复习 {len(to_recite)} 首诗词。按回车显示下一首，输入 q 退出。")
    idx = 0
    while to_recite:
        num, name = to_recite.pop()
        if (num, name) not in seen_poems:
            poem_key = f"{num}-{name}"
            poem_history = history.get(poem_key, {'count': 0, 'mastery_level': 1, 'last_review': None})
            if not isinstance(poem_history, dict):
                poem_history = {'count': poem_history, 'mastery_level': 1, 'last_review': None}
            
            print(f"\n第{idx+1}首：{name}（序号：{num}）")
            print(f"已背诵次数：{poem_history['count']}次，掌握程度：{poem_history.get('mastery_level', 1)}/6")
            
            recite_record.append((num, name))
            seen_poems.add((num, name))
            
            while True:
                try:
                    mastery = int(input("请评价掌握程度（1-6，1最低，6最高）：").strip())
                    if 1 <= mastery <= 6:
                        break
                    print("请输入1-6之间的数字。")
                except ValueError:
                    print("请输入有效的数字。")
            
            history[poem_key] = {
                'count': poem_history['count'] + 1,
                'mastery_level': mastery,
                'last_review': datetime.now()
            }
            idx += 1
            
            cmd = input("背诵完毕，按回车进入下一首，输入 q 退出：").strip().lower()
            if cmd == 'q':
                print("已退出。")
                break

    print("\n本次背诵记录：")
    for i, (num, name) in enumerate(recite_record, 1):
        poem_key = f"{num}-{name}"
        poem_data = history[poem_key]
        print(f"{i}. 序号：{num}，名称：{name}，已背诵次数：{poem_data['count']}次，掌握程度：{poem_data['mastery_level']}/6")
    
    save_history(history)

if __name__ == "__main__":
    main()